package setcarousel

import (
	"Student_Mental/DBconfing"
	"Student_Mental/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func returnErr(err error, c *gin.Context) {
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  err.Error(),
		})
	}
}

// ListData  轮播图列表
func ListData(c *gin.Context) {
	var carousel_list []model.Carousel
	sqlDb, _ := DBconfing.Mysql()
	rows, err := sqlDb.Query("SELECT * from Carousel")
	if err != nil {
		println("结果为空")
		return
	}
	//遍历打印
	for rows.Next() {
		var s model.Carousel
		err = rows.Scan(&s.Id, &s.Title, &s.Context, &s.Url, &s.Link, &s.CreateTime)
		data := model.Carousel{
			Id:         s.Id,
			Title:      s.Title,
			Context:    s.Context,
			Url:        s.Url,
			Link:       s.Link,
			StringTime: s.CreateTime.Format("2006-01-02 15:04:05"),
		}
		carousel_list = append(carousel_list, data)
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": carousel_list,
	})
	//用完关闭
	rows.Close()
	sqlDb.Close()
}

// Add 轮播图添加
func Add(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	var stu model.Carousel
	stu.Title = c.PostForm("Title")
	stu.Context = c.PostForm("Context")
	stu.Url = c.PostForm("Url")
	stu.Link = c.PostForm("Link")
	stu.CreateTime = time.Now()
	if stu.Title != "" {
		rs, err := sqlDb.Exec("insert into Carousel(title, context, url,link,create_time)values(?,?,?,?,?)", stu.Title, stu.Context, stu.Url, stu.Link, stu.CreateTime)
		returnErr(err, c)
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount > 0 {
			c.JSON(200, gin.H{
				"code": 0,
			})
		} else {
			returnErr(err, c)
		}
	}
	sqlDb.Close()
}

// Del  轮播图删除
func Del(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	id := c.Param("id")
	sqlStr := "delete from Carousel where id = ?"
	res, err := sqlDb.Exec(sqlStr, id)
	returnErr(err, c)
	reslist, _ := res.RowsAffected()
	if reslist > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 1,
		})
	}
	sqlDb.Close()
}

// Get   获取轮播图
func Get(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	id := c.Param("id")
	var s model.Carousel
	err := sqlDb.QueryRow("SELECT * FROM Carousel where id=?", id).Scan(&s.Id, &s.Title, &s.Context, &s.Url, &s.Link, &s.CreateTime)
	returnErr(err, c)
	c.HTML(200, "CarouselEdit.html", gin.H{
		"code": 0,
		"data": s,
	})
	sqlDb.Close()
}

// Edit 提交修改
func Edit(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	var stu model.Carousel
	id := c.PostForm("Id")
	stu.Title = c.PostForm("Title")
	stu.Context = c.PostForm("Context")
	stu.Url = c.PostForm("Url")
	stu.Link = c.PostForm("Link")
	if stu.Title != "" {
		rs, err := sqlDb.Exec("update Carousel set title=?, context=?, url=?,link=? where id=?", stu.Title, stu.Context, stu.Url, stu.Link, id)
		returnErr(err, c)
		row, err := rs.RowsAffected()
		returnErr(err, c)
		if row > 0 {
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "修改成功",
			})
		} else {
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "无修改",
			})
		}
	}
	sqlDb.Close()
}
